<!-- The exported code uses Tailwind CSS. Install Tailwind CSS in your dev environment to ensure all styles work. -->
<template>
  <div class="p-6">
    <!-- 标题和操作区 -->
    <div class="mb-6 flex items-center">
      <a
        @click="goToKnowledgeBaseManagement"
        class="mr-2 text-gray-500 hover:text-blue-600 cursor-pointer"
      >
        <el-icon>
          <Back />
        </el-icon>
      </a>
      <h2 class="text-2xl font-bold text-gray-800">文档上传</h2>
    </div>

    <!-- 拖拽上传区域 -->
    <div
      class="mb-6 border-2 border-dashed border-gray-300 rounded-lg p-8 bg-white text-center cursor-pointer hover:border-blue-500 transition-colors"
      :class="{ 'border-blue-500 bg-blue-50': isDragging }"
      @dragover.prevent="handleDragOver"
      @dragleave.prevent="handleDragLeave"
      @drop.prevent="handleDrop"
      @click="triggerFileInput"
    >
      <input
        ref="fileInput"
        type="file"
        multiple
        class="hidden"
        @change="handleFileChange"
        :accept="acceptedFileTypes.join(',')"
      />
      <div class="flex justify-center mb-4">
        <el-icon class="text-6xl text-blue-300">
          <Upload />
        </el-icon>
      </div>
      <h3 class="text-lg font-medium text-gray-800 mb-2">拖拽文件到此处或点击上传</h3>
      <p class="text-gray-500 mb-4">支持单个或批量上传文件，每个文件大小不超过 100MB</p>
      <button
        class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 cursor-pointer !rounded-button whitespace-nowrap"
      >
        <el-icon class="mr-2">
          <FolderOpened />
        </el-icon>
        点击选择文件
      </button>
      <p class="mt-4 text-sm text-gray-400">支持的文件类型：{{ selectedFileTypes.join('、') }}</p>
    </div>

    <!-- 上传配置区域 -->
    <div class="mb-6 bg-white rounded-lg shadow-sm p-6">
      <h3 class="text-lg font-medium text-gray-800 mb-6">上传配置</h3>
      <!-- 目标知识库 -->
      <div class="mb-8">
        <label class="block text-base font-medium text-gray-800 mb-3">目标知识库</label>
        <el-select 
          v-model="targetKnowledgeBase" 
          placeholder="请选择目标知识库" 
          class="w-full"
          :loading="loadingKnowledgeBases"
          @change="handleKnowledgeBaseChange"
        >
          <el-option 
            v-for="kb in knowledgeBases" 
            :key="kb.id" 
            :label="kb.name" 
            :value="kb.id" 
          />
        </el-select>
        <div class="mt-2 flex justify-end">
          <el-button 
            type="primary" 
            link 
            @click="goToKnowledgeBaseManagement"
          >
            <el-icon class="mr-1">
              <Plus />
            </el-icon>
            创建新知识库
          </el-button>
        </div>
      </div>
      <!-- 文件类型筛选 -->
      <div class="mb-8">
        <label class="block text-base font-medium text-gray-800 mb-3">支持的文件类型</label>
        <el-checkbox-group v-model="selectedFileTypes">
          <div class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-5 gap-4">
            <el-checkbox label="PDF" border class="!rounded-button" />
            <el-checkbox label="Word" border class="!rounded-button" />
            <el-checkbox label="Excel" border class="!rounded-button" />
            <el-checkbox label="PPT" border class="!rounded-button" />
          </div>
        </el-checkbox-group>
      </div>
      <!-- 高级设置 -->
      <div class="border-t border-gray-100 pt-6">
        <h4 class="text-base font-medium text-gray-800 mb-6">高级设置</h4>
        <!-- 提取文本设置 -->
        <div class="bg-gray-50 rounded-lg p-4 mb-4">
          <div class="flex items-center justify-between">
            <div>
              <label class="block text-base font-medium text-gray-800 mb-1">提取文本</label>
              <span class="text-sm text-gray-600">从 PDF、图片等文件中提取文本内容</span>
            </div>
            <el-switch v-model="extractText" class="scale-110" />
          </div>
        </div>
        <!-- 语言设置 -->
        <div class="bg-gray-50 rounded-lg p-4">
          <label class="block text-base font-medium text-gray-800 mb-3">文档主要语言</label>
          <el-select v-model="documentLanguage" placeholder="请选择文档语言" class="w-full">
            <el-option label="中文" value="zh" />
            <el-option label="英文" value="en" />
            <el-option label="自动检测" value="auto" />
          </el-select>
        </div>
      </div>
    </div>

    <!-- 文件列表 -->
    <div v-if="fileList.length > 0" class="mb-6 bg-white rounded-lg shadow-sm overflow-hidden">
      <div class="p-4 border-b border-gray-100 flex justify-between items-center">
        <h3 class="text-lg font-medium text-gray-800">上传文件列表 ({{ fileList.length }})</h3>
        <div class="flex space-x-2">
          <button 
            v-if="fileList.some(file => file.status === 'pending')" 
            @click="startUpload" 
            class="flex items-center text-white bg-blue-600 hover:bg-blue-700 px-3 py-1 rounded-md"
            :disabled="isUploading"
          >
            <el-icon class="mr-1">
              <Upload />
            </el-icon>
            <span>开始上传</span>
          </button>
          <button @click="clearFileList" class="text-gray-500 hover:text-red-500 cursor-pointer">
            <el-icon>
              <Delete />
            </el-icon>
            <span class="ml-1">清空</span>
          </button>
        </div>
      </div>
      <el-table :data="fileList" style="width: 100%">
        <el-table-column label="文件名" min-width="280">
          <template #default="{ row }">
            <div class="flex items-center">
              <el-icon class="mr-2 text-blue-500">
                <Document />
              </el-icon>
              <span class="truncate">{{ row.name }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="大小" width="120">
          <template #default="{ row }">
            {{ formatFileSize(row.size) }}
          </template>
        </el-table-column>
        <el-table-column label="上传进度" width="200">
          <template #default="{ row }">
            <el-progress
              :percentage="row.progress"
              :status="
                row.status === 'error' ? 'exception' : row.status === 'success' ? 'success' : ''
              "
            />
          </template>
        </el-table-column>
        <el-table-column label="状态" width="120">
          <template #default="{ row }">
            <el-tag
              :type="
                row.status === 'success' ? 'success' : row.status === 'error' ? 'danger' : 'info'
              "
              size="small"
            >
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row, $index }">
            <el-button v-if="row.status === 'error'" type="primary" link @click="retryUpload(row)">
              重试
            </el-button>
            <el-button v-if="row.status !== 'uploading'" type="danger" link @click="removeFile($index)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Document,
  Setting,
  ChatDotRound,
  Picture,
  VideoPlay,
  Search,
  Plus,
  ShoppingCart,
  User,
  Lock,
  Medal,
  Wallet,
  Upload,
  Files,
  View,
  EditPen,
  Delete,
  MoreFilled,
  Timer,
  Refresh,
  WarningFilled,
  Back,
  FolderOpened,
  Folder,
} from '@element-plus/icons-vue'

import { useRouter1 } from '../utils/useRoute'
import { listKnowledge, getKnowledgeSts, uploadToBailian } from '../api/knowledge'
import { uploadToKnowledgeOss } from '../utils/upload'

const {
  goToHome,
  goToDocumentUpload,
  goToKnowledgeBaseManagement,
  goToMemberCenter,
  goToNotificationSettings,
  goToOrder,
  goToPointsManagement,
  goToSecuritySettings,
  goToUser,
  goToAiChat,
  goToAiDrawing,
  goToProduct,
} = useRouter1()

// 知识库列表
const knowledgeBases = ref([])
const loadingKnowledgeBases = ref(false)
const selectedKnowledgeBase = ref(null)

// 上传配置
const targetKnowledgeBase = ref('')
const selectedFileTypes = ref(['PDF', 'Word', 'Excel', 'PPT'])
const extractText = ref(true)
const documentLanguage = ref('auto')

// 文件上传相关
const fileInput = ref(null)
const fileList = ref([])
const isDragging = ref(false)
const isUploading = ref(false)

// 计算接受的文件类型
const acceptedFileTypes = computed(() => {
  const typeMap = {
    PDF: '.pdf',
    Word: '.doc,.docx',
    Excel: '.xls,.xlsx',
    PPT: '.ppt,.pptx',
  }
  return selectedFileTypes.value.map((type) => typeMap[type]).filter(Boolean)
})

// 获取知识库列表
const fetchKnowledgeBases = async () => {
  try {
    loadingKnowledgeBases.value = true
    const params = {
      page: {
        page: 1,
        limit: 100,
        order: 'DESC',
        field: 'createTime'
      }
    }
    
    const response = await listKnowledge(params)
    knowledgeBases.value = response.data || []
  } catch (error) {
    console.error('获取知识库列表失败:', error)
    ElMessage.error('获取知识库列表失败')
    knowledgeBases.value = []
  } finally {
    loadingKnowledgeBases.value = false
  }
}

// 处理知识库选择变更
const handleKnowledgeBaseChange = (id) => {
  selectedKnowledgeBase.value = knowledgeBases.value.find(kb => kb.id === id)
}

// 触发文件选择
const triggerFileInput = () => {
  fileInput.value?.click()
}

// 处理拖拽事件
const handleDragOver = (e) => {
  isDragging.value = true
}

const handleDragLeave = (e) => {
  isDragging.value = false
}

const handleDrop = (e) => {
  isDragging.value = false
  if (e.dataTransfer?.files) {
    addFiles(e.dataTransfer.files)
  }
}

// 处理文件选择
const handleFileChange = (e) => {
  const input = e.target
  if (input.files) {
    addFiles(input.files)
  }
  // 重置input，以便可以重复选择同一文件
  input.value = ''
}

// 添加文件到列表
const addFiles = (files) => {
  const newFiles = []
  for (let i = 0; i < files.length; i++) {
    const file = files[i]
    // 检查文件类型是否支持
    const fileExt = '.' + file.name.split('.').pop()?.toLowerCase()
    const isAccepted = acceptedFileTypes.value.some((types) =>
      types.split(',').some((ext) => ext === fileExt || ext === '.' + file.type.split('/').pop()),
    )
    if (!isAccepted) {
      // 显示错误提示
      ElMessage.error(`不支持的文件类型: ${file.name}`)
      continue
    }
    // 检查文件大小
    if (file.size > 100 * 1024 * 1024) {
      // 100MB
      ElMessage.error(`文件过大: ${file.name}`)
      continue
    }
    newFiles.push({
      id: Date.now() + '-' + Math.random().toString(36).substr(2, 9),
      name: file.name,
      size: file.size,
      type: file.type,
      file: file,
      progress: 0,
      status: 'pending',
      realName: '', // OSS上传后的真实文件名
    })
  }
  fileList.value.push(...newFiles)
}

// 移除文件
const removeFile = (index) => {
  fileList.value.splice(index, 1)
}

// 清空文件列表
const clearFileList = () => {
  if (isUploading.value) {
    ElMessage.warning('文件正在上传中，无法清空')
    return
  }
  
  ElMessageBox.confirm('确定要清空所有上传文件吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      fileList.value = []
    })
    .catch(() => {
      // 取消操作
    })
}

// 格式化文件大小
const formatFileSize = (size) => {
  if (size < 1024) {
    return size + ' B'
  } else if (size < 1024 * 1024) {
    return (size / 1024).toFixed(1) + ' KB'
  } else {
    return (size / (1024 * 1024)).toFixed(1) + ' MB'
  }
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    'pending': '待上传',
    'uploading': '上传中',
    'success': '成功',
    'error': '失败',
    'processing': '处理中'
  }
  return statusMap[status] || status
}

// 上传单个文件
const uploadFile = async (file) => {
  try {
    file.status = 'uploading'
    
    // 使用 uploadToKnowledgeOss 上传文件
    const result = await uploadToKnowledgeOss(file.file, (progress) => {
      file.progress = Math.floor(progress * 100)
    })
    
    // 上传成功
    file.progress = 100
    file.status = 'processing'
    
    // 获取文件名
    const ossFileName = result.name
    file.realName = ossFileName
    
    return {
      originalName: file.name,
      realName: ossFileName
    }
  } catch (error) {
    console.error('上传文件失败:', error)
    file.status = 'error'
    file.errorMessage = '上传失败，请重试'
    throw error
  }
}

// 提交到百炼知识库
const submitToBailian = async (fileInfos) => {
  try {
    if (!selectedKnowledgeBase.value || !selectedKnowledgeBase.value.id) {
      throw new Error('知识库ID不存在')
    }
    
    // 处理文件信息，确保 realName 只包含文件名
    const processedFileInfos = fileInfos.map(info => ({
      originalName: info.originalName,
      realName: info.realName.split('/').pop() // 只保留文件名部分
    }));
    
    const params = {
      id: selectedKnowledgeBase.value.id,
      fileNames: processedFileInfos
    }
    
    await uploadToBailian(params)
    
    // 更新文件状态
    fileInfos.forEach(info => {
      const file = fileList.value.find(f => f.realName === info.realName)
      if (file) {
        file.status = 'success'
      }
    })
    
    return true
  } catch (error) {
    console.error('提交到百炼知识库失败:', error)
    
    // 更新文件状态
    fileInfos.forEach(info => {
      const file = fileList.value.find(f => f.realName === info.realName)
      if (file) {
        file.status = 'error'
        file.errorMessage = '提交到知识库失败'
      }
    })
    
    throw error
  }
}

// 重试上传
const retryUpload = async (file) => {
  file.progress = 0
  file.status = 'pending'
  file.errorMessage = ''
  
  // 如果当前没有其他上传任务，则立即开始上传
  if (!isUploading.value) {
    startUpload()
  }
}

// 开始上传
const startUpload = async () => {
  if (fileList.value.length === 0) {
    ElMessage.warning('请选择文件')
    return
  }
  
  if (!targetKnowledgeBase.value) {
    ElMessage.warning('请先选择目标知识库')
    return
  }
  
  if (isUploading.value) {
    ElMessage.warning('文件正在上传中')
    return
  }
  
  try {
    isUploading.value = true
    
    // 筛选待上传的文件
    const pendingFiles = fileList.value.filter(file => file.status === 'pending')
    
    if (pendingFiles.length === 0) {
      ElMessage.info('没有待上传的文件')
      isUploading.value = false
      return
    }
    
    // 上传文件到OSS
    const uploadPromises = pendingFiles.map(file => uploadFile(file))
    const fileInfos = await Promise.all(uploadPromises)
    
    // 提交到百炼知识库
    await submitToBailian(fileInfos)
    
    // 统计上传结果
    const successCount = fileList.value.filter(f => f.status === 'success').length
    const errorCount = fileList.value.filter(f => f.status === 'error').length
    
    if (errorCount === 0) {
      ElMessage.success(`所有 ${successCount} 个文件上传成功，等待解析完成`)
    } else {
      ElMessage.warning(`${successCount} 个文件上传成功，${errorCount} 个文件上传失败`)
    }
  } catch (error) {
    console.error('上传过程中发生错误:', error)
    ElMessage.error('上传失败，请重试')
  } finally {
    isUploading.value = false
  }
}

// 页面加载时获取知识库列表
onMounted(() => {
  fetchKnowledgeBases()
})
</script>
<style scoped>
/* 修复输入框样式 */
input:focus {
  outline: none;
}

/* 去除number输入框的箭头 */
input[type='number']::-webkit-inner-spin-button,
input[type='number']::-webkit-outer-spin-button {
  -webkit-appearance: none;
  margin: 0;
}

input[type='number'] {
  -moz-appearance: textfield;
}

/* 自定义样式 */
.upload-area {
  transition: all 0.3s ease;
}

.upload-area:hover {
  border-color: #3b82f6;
  background-color: #f0f7ff;
}
</style>
